<template>
  <div>

    <div>
      <el-input size="small" clearable v-model="listQuery.param.name" style="width: 200px;margin-top:10px;margin-right:10px;" placeholder="请输入名称" />
      <el-select size="small" style="margin-top:10px;margin-right:10px;" v-model="listQuery.param.createUser" clearable placeholder="请选择">
        <el-option v-for="item in userRole" :key="item.userId" :label="item.userName" :value="item.userId">
          <span :class="{lineThrough:item.status === 100}" style="float: left">{{ item.userName }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.roles }}</span>
        </el-option>
      </el-select>
      <el-date-picker style="margin-top:10px;margin-right:10px;" size="small" v-model="dateFilter" type="daterange" range-separator="-" format="yyyy-MM-dd" value-format="yyyy-MM-dd" @change="dateChange" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      <el-select style="margin-top:10px;margin-right:10px;" size="small" v-model="listQuery.param.status">
        <el-option label="全部" :value="-1" />
        <el-option label="提交" :value="0" />
        <el-option label="回退" :value="100" />
      </el-select>
      <el-button size="small" type="primary" icon="el-icon-search" style="margin-top:10px;margin-right:10px;" @click="handleFilter">
        查询
      </el-button>
      <el-button v-if="add_project_bill_button_status" size="small" icon="el-icon-plus" style="margin-left:0px;margin-top:10px;margin-right:10px;" @click="handleAdd">
        增加
      </el-button>
    </div>

    <el-table :data="billLists" style="margin-top:10px">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <span :key="image" v-for="(image, index) in scope.row.images">
            <el-image style="width:30px;height:30px;margin-left:10px" :src="image | projectBillInfoMinImgUrl" :preview-src-list="getImgList(scope.row.images, index)">
            </el-image>
          </span>
        </template>
      </el-table-column>

      <el-table-column label="单据信息">
        <el-table-column v-if="false" prop="id" />
        <el-table-column prop="billNo" label="单号" width="200" show-overflow-tooltip />
        <el-table-column prop="name" label="名称" width="200" show-overflow-tooltip />
        <el-table-column prop="quantity" label="数量" width="200" />
        <el-table-column prop="unitPrice" label="单价" width="200" />
        <el-table-column prop="unit" label="单位" width="200" />
        <el-table-column prop="totalPrice" label="总价格" width="200" />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column prop="createUser" label="创建人" width="200" />
        <el-table-column prop="billDesc" label="单据说明" width="200" show-overflow-tooltip />
      </el-table-column>
      <!-- <el-table-column label="确认信息">
        <el-table-column prop="confirmUser" label="确认人" width="200" />
        <el-table-column prop="confirmTime" label="确认时间" width="200" />
      </el-table-column> -->
      <el-table-column label="回退信息">
        <el-table-column prop="returnUser" label="回退人" width="200" />
        <el-table-column prop="returnTime" label="回退时间" width="200" />
        <el-table-column prop="returnDesc" label="回退原因" width="200" />
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 0">提交</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">确认</el-tag>
          <el-tag v-else-if="scope.row.status === 100" type="danger">回退</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="300" v-if="upd_project_bill_button_status || del_project_bill_button_status || approval_project_bill_button_status">
        <template slot-scope="scope">
          <el-button v-if="upd_project_bill_button_status" size="small" icon="el-icon-edit" type="primary" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-if="del_project_bill_button_status" size="small" icon="el-icon-delete" type="danger" @click="handleDelete(scope.row)">删除</el-button>

          <el-popover v-if="approval_project_bill_button_status" trigger="click" placement="left" width="160" :ref="'popover' + scope.row.id" @after-leave="checkHide('billCheck' + scope.row.id)">
            <el-form :model="approvalBillForm" :rules="approvalBillFormRules" :ref="'billCheck' + scope.row.id">
              <!-- <el-form-item prop="state">
                <el-select v-model="approvalBillForm.state">
                  <el-option label="确认" :value="1" />
                  <el-option label="回退" :value="0" />
                </el-select>
              </el-form-item> -->
              <el-form-item prop="desc">
                <el-input placeholder="审批理由" v-model="approvalBillForm.desc" />
              </el-form-item>
            </el-form>
            <div style="text-align: right; margin: 0">
              <el-button type="primary" size="mini" @click="checkFromSubmit('billCheck' + scope.row.id, scope.row.id)">确定</el-button>
            </div>
            <el-button slot="reference" style="margin-left:10px" type="warning" icon="el-icon-edit" size='mini'>退审</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10, 20, 40, 100]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="totalBillCount">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="45%" :before-close="handleCancel">
      <el-form :rules="rules" :model="form" ref="form" label-width="100px">
        <el-form-item label="单号" prop="billNo">
          <el-input v-model="form.billNo" placeholder="请输入单号" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input type="number" v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input type="number" v-model="form.unitPrice" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <el-upload action="" list-type="picture-card" :file-list="picLists" :on-preview="handlePictureCardPreview" :on-remove="handlePictureCardRemove" :before-upload="beforeUploadImages" :http-request="handlePictureCardHttpRequest">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <!-- <el-form-item label="图片" prop="images">
          <div class="image_form">
            <el-upload class="image_card" v-for="(item, index) in form.images" :key="item" action="" list-type="picture-card" :show-file-list="false" :before-upload="beforeUploadImages" :http-request="(d) => uploadImages(d, index)">
              <img class="imageSize" :src="item | projectBillInfoMinImgUrl">
            </el-upload>
            <el-upload v-if="form.images.length < 9" action="" class="image_card" list-type="picture-card" :show-file-list="false" :before-upload="beforeUploadImages" :http-request="uploadImages">
              <i class="el-icon-plus"></i>
            </el-upload>
          </div>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="handleCancel()">
          取 消
        </el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="handleCreate()">
          确 定
        </el-button>
        <el-button v-if="dialogStatus=='update'" type="primary" @click="handleUpdate()">
          确 定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>

import { mapGetters } from 'vuex';
import {
  addBuildingSiteBill, updBuildingSiteBill, getBuildingSiteBill, delBuildingSiteBill, returnBackBuildingSiteBill
} from '@/api/buildingSiteBill'
import { getAllProjectUserInfo } from '@/api/projectUserInfo'
import { projectBillInfoUpload } from '@/api/upload'

export default {
  name: 'ProjectBillPage',
  props: {
    ProjectId: {
      type: Number
    }
  },
  watch: {
    ProjectId(newVal, oldVal) {
      console.log("bill old: " + oldVal + ", new: " + newVal + ", watch: " + this.isWatch);
      this.projectId = newVal;
      this.listQuery.param.projectId = newVal;
      this.form.projectId = newVal;
      if (newVal === 0) {
        this.billLists = [];
        this.userRole = [];
        this.totalBillCount = 0;
      } else if (this.isWatch) {
        this.getBuildingSiteBillList();
        this.getAllUserRoleInfo();
      }
    }
  },
  computed: {
    ...mapGetters(["elements"])
  },
  created() {
    if (this.elements['add_project_bill']) {
      this.add_project_bill_button_status = true;
    }
    if (this.elements['upd_project_bill']) {
      this.upd_project_bill_button_status = true;
    }
    if (this.elements['del_project_bill']) {
      this.del_project_bill_button_status = true;
    }
    if (this.elements['approval_project_bill']) {
      this.approval_project_bill_button_status = true;
    }
  },
  data() {
    var checkNumberRange = (rule, value, callback) => {
      console.log("checkNumberRange", rule, value, typeof value)
      callback();
    };
    var checkArray = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error('请选择文件'));
      }
      callback();
    };
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      picLists: [],

      dateFilter: [],
      isWatch: false,
      textMap: {
        create: "创建",
        update: "修改"
      },
      dialogFormVisible: false,
      dialogStatus: "",

      projectId: 0,
      listQuery: {
        page: 1,
        size: 10,
        param: {
          projectId: undefined,
          billNo: undefined,
          name: undefined,
          createUser: undefined,
          startTime: undefined,
          endTime: undefined,
          status: -1
        }
      },
      userQuery: {
        page: 1,
        size: 2147483640,
        param: {}
      },
      userRole: [],
      billLists: [],
      totalBillCount: undefined,
      form: {
        projectId: undefined,
        id: undefined,
        name: undefined,
        quantity: undefined,
        unit: undefined,
        unitPrice: undefined,
        images: []
      },
      rules: {
        billNo: [
          { required: true, message: "请填写单号", trigger: "blur" },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: "请填写名称", trigger: "blur" },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请填写数量', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        images: [
          { required: true, message: '请选择文件', trigger: 'blur' },
          { validator: checkArray, trigger: 'blur' }
        ]
      },

      approvalBillForm: {
        id: undefined,
        desc: undefined
      },
      approvalBillFormRules: {
        desc: [
          { max: 200, message: '长度大于 200 个字符', trigger: 'blur' }
        ]
      },

      add_project_bill_button_status: false,
      upd_project_bill_button_status: false,
      del_project_bill_button_status: false,
      approval_project_bill_button_status: false
    }
  },
  mounted() {

  },
  methods: {
    show() {
      this.isWatch = true;
      if (this.projectId === 0) {
        this.billLists = [];
        this.userRole = [];
        this.totalBillCount = 0;
        return;
      }
      this.getBuildingSiteBillList();
      this.getAllUserRoleInfo();
    },
    hide() {
      this.isWatch = false;
    },
    getImgList(images, index) {
      var imgLists = [];
      for (let i = index; i < images.length; i++) {
        imgLists.push(this.$options.filters['projectBillInfoImgUrl'](images[i]));
      }
      for (let i = 0; i < index; i++) {
        imgLists.push(this.$options.filters['projectBillInfoImgUrl'](images[i]));
      }
      return imgLists;
    },
    getBuildingSiteBillList() {
      getBuildingSiteBill(this.listQuery).then(resp => {
        this.billLists = resp.datas.datas;
        this.totalBillCount = resp.datas.total;
      });
    },
    getAllUserRoleInfo() {
      getAllProjectUserInfo(this.projectId).then(resp => {
        this.userRole = resp.datas;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getBuildingSiteBillList();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getBuildingSiteBillList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getBuildingSiteBillList();
    },

    // 上传图片接口
    uploadImages(d, oldIndex) {
      if (oldIndex === undefined || oldIndex < 0) {
        oldIndex = this.form.images.length;
      }
      projectBillInfoUpload(d.file).then(resp => {
        this.form.images.splice(oldIndex, 1, resp.datas);
      });
    },
    // 图片上传前校验，最多只能上传9张照片
    beforeUploadImages(file) {
      return this.form.images.length < 9;
    },

    handleAdd() {
      this.resetForm();
      this.dialogFormVisible = true;
      this.dialogStatus = 'create';
    },
    handleCreate() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false;
        }
        addBuildingSiteBill(this.form).then(resp => {
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000,
            customClass: 'notityClass'
          });
          // 关闭窗口
          this.handleCancel();
          // 更新列表
          this.getBuildingSiteBillList();
        });
      });
    },
    handleEdit(row) {
      this.resetForm();
      this.dialogFormVisible = true;
      this.dialogStatus = 'update';
      this.$nextTick(() => {
        this.form = {
          projectId: this.projectId,
          id: row.id,
          billNo: row.billNo,
          name: row.name,
          quantity: row.quantity,
          unit: row.unit,
          unitPrice: row.unitPrice,
          images: []
        }
        row.images.forEach(x => {
          this.form.images.push(x);
          this.picLists.push({ path: x, url: this.$options.filters['projectBillInfoMinImgUrl'](x) })
        })
        console.log("编辑打开弹窗", row.images, this.form, this.picLists)
      })
    },
    handleUpdate() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return false;
        }
        updBuildingSiteBill(this.form).then(resp => {
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000,
            customClass: 'notityClass'
          });
          // 关闭窗口
          this.handleCancel();
          // 更新列表
          this.getBuildingSiteBillList();
        })
      });
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delBuildingSiteBill(row.id).then(resp => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000,
            customClass: 'notityClass'
          });
        })
      });
    },
    handleCancel() {
      this.dialogFormVisible = false;
      this.dialogStatus = undefined;
      this.resetForm();
      this.picLists = [];
    },
    resetForm() {
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    dateChange(val) {
      if (val) {
        this.listQuery.param.startTime = this.dateFilter[0];
        this.listQuery.param.endTime = this.dateFilter[1];
      }
      else {
        this.listQuery.param.startTime = undefined;
        this.listQuery.param.endTime = undefined;
      }
    },

    checkFromSubmit(formname, id) {
      this.approvalBillForm.id = id;
      this.$refs[formname].validate((valid) => {
        if (!valid) {
          return false;
        }
        returnBackBuildingSiteBill(this.approvalBillForm).then(resp => {
          this.$notify({
            title: "成功",
            message: "审批成功",
            type: "success",
            duration: 2000
          });
          this.$refs['popover' + id].doClose();
          this.getBuildingSiteBillList();
        })
      });
    },

    checkHide(formname) {
      if (this.$refs[formname]) {
        this.$refs[formname].resetFields();
      }
    },



    // 图片预览方法回调
    handlePictureCardPreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = this.$options.filters['projectBillInfoImgUrl'](file.path);
      console.log("on-preview 方法触发", file, this.picLists);
    },

    handlePictureCardRemove(file, fileList) {
      console.log("on-remove 方法触发", file, fileList, this.picLists);
      this.picLists.forEach((item, index, arr) => {
        if (item.path === file.path) {
          this.picLists.splice(index, 1)
        }
      });

      this.form.images.forEach((item, index) => {
        if (item === file.path) {
          this.form.images.splice(index, 1)
        }
      })
      console.log("on-remove 方法完成", this.picLists, this.form.images);
    },

    handlePictureCardHttpRequest(d) {
      projectBillInfoUpload(d.file).then(resp => {
        var path = resp.datas;
        var url = this.$options.filters['projectBillInfoMinImgUrl'](path);
        this.form.images.push(path);
        this.picLists.push({ path: path, url: url });
        console.log("http-request 文件上传成功", this.form.images, this.picLists);
      });
    },

    handlePictureCardBeforeUpload(d) {
    }

  }
}
</script>

<style>
.lineThrough {
  text-decoration: line-through;
}
.image_card {
  display: inline-block;
}
.image_card .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}
.imageSize {
  width: 98px;
  height: 98px;
  border-radius: 6px;
}
.image_form :not(:last-child) {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>